package com.demo.client;

import java.io.IOException;
import java.util.List;

import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.async.TAsyncClientManager;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingSocket;
import org.apache.thrift.transport.TNonblockingTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

import com.demo.thrift.InvalidException;
import com.demo.thrift.Status;
import com.demo.thrift.Student;
import com.demo.thrift.ThriftMysqlService;
import com.demo.thrift.ThriftMysqlService.AsyncClient.queryAllUser_call;

/**
 * 调用异步非阻塞I/O服务客户端 
 *
 * @author HuangKe
 * @date 2017年3月7日
 * @company Copyright © 2007-2016 www.zgxcw.com All Rights Reserved
 */
public class AsyncNoBlockingClient {
	public static String ip = "localhost";
	public static int port = 8899;
	public static int time_out = 3000;
	public static void main(String[] args) throws InterruptedException {
		AsyncNoBlockingClient.sync();
		AsyncNoBlockingClient.async();
		Thread.sleep(3000);//异步有延时
	}
	
	/**
	 * 同步调用异步服务
	 */
	public static void sync(){
		TTransport transport = new TFramedTransport(new TSocket(ip, port, time_out));  
        TProtocol protocol = new TCompactProtocol(transport);  
        ThriftMysqlService.Client client = new ThriftMysqlService.Client(protocol);  
        try {
			transport.open();
			Student s = new Student(123, "Mr.HK", "123456", Status.OK);
			client.addUser(s);
			System.out.println(client.queryAllUser().size());
		} catch (TTransportException e) {
			e.printStackTrace();
		} catch (InvalidException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			transport.close();
		}
	}
	
	/**
	 * 异步调用查询列表
	 */
	public static void async(){
		TNonblockingTransport transport = null;
		try {
			TAsyncClientManager clientManager = new TAsyncClientManager();  
			transport = new TNonblockingSocket(ip, port, time_out);  
			TProtocolFactory protocol = new TCompactProtocol.Factory();  
			ThriftMysqlService.AsyncClient asyncClient = new ThriftMysqlService.AsyncClient(protocol, clientManager, transport);
			asyncClient.queryAllUser(new AsyncMethodCallback<List<Student>>() {
				
				public void onError(Exception exception) {
					exception.printStackTrace();
				}
				
				public void onComplete(List<Student> response) {
					System.out.println("response: " + response.toString());
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
}

